<template>
    <el-dialog :visible.sync="value" :before-close="() => $emit('input', false)" class="data-menu-wrapper">
      <template slot="title">
        数据权限设置
      </template>
      <el-row>
        <el-col :span="6">
          <el-menu
            default-active="1-1"
            :default-openeds="defaultOpeneds"
            :collapse="false"
            @select='selectEvent'>
            <el-submenu index="1">
              <template slot="title">
                <span>会员管理</span>
              </template>
              <el-menu-item index="1-1">操作审核</el-menu-item>
            </el-submenu>
            <el-submenu index="2">
              <template slot="title">
                <span>代理管理</span>
              </template>
              <el-menu-item index="2-1">操作审核</el-menu-item>
            </el-submenu>
            <el-submenu index="3">
              <template slot="title">
                <span>财务管理</span>
              </template>
              <el-submenu index="3-1">
                  <template slot="title">
                    <span>充值管理</span>
                  </template>
                <el-menu-item index="3-1-1">充值补单审核</el-menu-item>
              </el-submenu>
              <el-submenu index="3-2">
                <template slot="title">
                  <span>提现管理</span>
                </template>
                <el-menu-item index="3-2-1">异常提现处理</el-menu-item>
                <el-menu-item index="3-2-2">提现操作审核</el-menu-item>
              </el-submenu>
              <el-submenu index="4">
                <template slot="title">
                  <span>资金调整审核</span>
                </template>
                <el-menu-item index="4-1">资金调整审核</el-menu-item>
              </el-submenu>
            </el-submenu>
          </el-menu>
        </el-col>
        <el-col :span="18" class="el-col-wrapper">
          <div class="select-all">
            <el-checkbox @change="allSelect" v-model="selectAllValue"></el-checkbox>
          </div>
          <el-checkbox-group v-model="checkList">
            <el-table
              border
              :data="tableData"
              v-loading="loading"
              :span-method="getSpanMethod"
              element-loading-text="加载中...">
              <el-table-column :label="item.title" align="left"
                               v-for="item in tableTitle" :key="item.parentId"
                               :prop="String(item.parentId)">
                <template slot-scope="{row}">
                  <el-checkbox :label="row[item.title].menuId" :key="row[item.title].menuId" @change="checkRelevance(row[item.title].menuId,row[item.title].parentId)">{{row[item.title].name}}</el-checkbox>
                </template>
              </el-table-column>

              <el-table-column :label="'数据权限'" align="left">
                <template slot-scope="{row}">
                  <el-checkbox v-for="itemSec in row['数据权限']" :key="itemSec.menuId"  :label="itemSec.menuId" @change="checkRelevance(itemSec.menuId,itemSec.parentId)">{{itemSec.name}}</el-checkbox>
                </template>
              </el-table-column>
            </el-table>
          </el-checkbox-group>
          <div class="btn-groups">
            <el-button size="medium" @click="$emit('input', false)">取消</el-button>
            <el-button type="primary" size="medium" @click="savePermissionList">确定</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
</template>

<script>
import { form, grid, dialog } from '@/build';
import getCommand from '@/mixins/getCommand';
import {
  authDataPermissionListGetApi,
  authDataPermissionListSaveApi,
} from '@/services/api/permission';

export default {
  name: 'permission-tree',
  mixins: [getCommand, form],
  components: {
  },
  props: {
    value: Boolean,
    jobId: Number,
  },
  data() {
    return {
      defaultOpeneds: ['1', '2', '3', '3-1', '3-2', '4'],
      checkList: [],
      checkListCopy: [],
      tableTitle: [],
      tableData: [],
      rowObj: {},
      sonArray: [],
      firstTableTitle: '',
      firstNodeObj: {},
      permissionList: [],
      flattenPermissionList: [],
      allPermissionList: [],
      allMenuId: [],
      selectAllValue: false,
      memAuditTree: [],
      agenAuditTree: [],
      rechargeReplenishAuditTree: [],
      abnormalWithdrawalHandle: [],
      withdrawalHandleAudit: [],
      moneyAdjustAudit: [],
      form: {
        menuList: [],
        jobId: this.jobId,
      },
    };
  },
  mounted() {
    this.bindGet(authDataPermissionListGetApi, 'permissionList', {
      action: 'getPermissionList',
      sendingData: { jobId: this.jobId },
      callback: ([result, data]) => {
        if (result) {
          this.allPermissionList = this.doFlattenPermissionList(data);
          this.memAuditTree = _.find(this.allPermissionList, { menuId: 100 }).children;
          this.agenAuditTree = _.find(this.allPermissionList, { menuId: 200 }).children;
          this.rechargeReplenishAuditTree = _.find(this.allPermissionList, { menuId: 30000 }).children;
          this.abnormalWithdrawalHandle = _.find(this.allPermissionList, { menuId: 30100 }).children;
          this.withdrawalHandleAudit = _.find(this.allPermissionList, { menuId: 30101 }).children;
          this.moneyAdjustAudit = _.find(this.allPermissionList, { menuId: 30200 }).children;

          this.selectEvent('1-1');
          _.each(this.allPermissionList, (item) => {
            if (item.selected === 1) {
              this.checkList.push(item.menuId);
            }
          });
          this.checkList = _.difference(this.checkList, [1, 100, 2, 200, 3, 300, 30000, 301, 30100, 30101, 302, 30200]);
          this.$nextTick(() => {
            this.isAllSelect();
          });
        } else {
          this.$notify({
            title: data.message,
            type: 'error',
            duration: 2000,
          });
        }
      },
    });
    this.doGet({ action: 'getPermissionList' });

    this.bindSave(authDataPermissionListSaveApi, 'savePermissionList', 'form', {
      afterSuccess: ([result, data]) => {
        if (result) {
          this.$emit('input', false);
        }
      },
    });
  },
  computed: {
  },
  methods: {
    selectEvent(index) {
      this.tableData = [];
      this.tableTitle = [];
      // this.checkList = [];
      this.firstTableTitle = '';
      this.firstNodeObj = {};
      switch (index) {
        case '1-1':
          this.getTableTitle(this.memAuditTree);
          this.flattenPermissionList = this.doFlattenPermissionList(this.memAuditTree);
          break;
        case '2-1':
          this.getTableTitle(this.agenAuditTree);
          this.flattenPermissionList = this.doFlattenPermissionList(this.agenAuditTree);
          break;
        case '3-1-1':
          this.getTableTitle(this.rechargeReplenishAuditTree);
          this.flattenPermissionList = this.doFlattenPermissionList(this.rechargeReplenishAuditTree);
          break;
        case '3-2-1':
          this.getTableTitle(this.abnormalWithdrawalHandle);
          this.flattenPermissionList = this.doFlattenPermissionList(this.abnormalWithdrawalHandle);
          break;
        case '3-2-2':
          this.getTableTitle(this.withdrawalHandleAudit);
          this.flattenPermissionList = this.doFlattenPermissionList(this.withdrawalHandleAudit);
          break;
        case '4-1':
          this.getTableTitle(this.moneyAdjustAudit);
          this.flattenPermissionList = this.doFlattenPermissionList(this.moneyAdjustAudit);
          break;
      }
      this.allMenuId = this.getAllMenuId();
      this.isAllSelect();
    },
    isAllSelect() {
      if (_.difference(this.allMenuId, this.checkList).length === 0) {
        this.selectAllValue = true;
      } else {
        this.selectAllValue = false;
      }
    },
    allSelect(checked) {
      if (checked) {
        this.checkList = this.checkList.concat(this.allMenuId);
      } else {
        this.checkList = _.difference(this.checkList, this.allMenuId);
      }
    },
    getAllMenuId() {
      const allMenuId = [];
      _.each(this.flattenPermissionList, (item) => {
        allMenuId.push(item.menuId);
      });
      return allMenuId;
    },
    checkRelevance(menuId, parentId) {
      const isChecked = window.event.target.checked;
      if (isChecked) {
        this.pushAllparentsId(menuId);
      } else {
        const selectedNode = _.find(this.flattenPermissionList, { menuId });
        // 点击后该结点下的子节点都取消选中
        this.unSelecteSonNode([selectedNode]);
      }
      this.isAllSelect();
    },
    pushAllparentsId(menuId) {
      const selectedNode = _.find(this.allPermissionList, { menuId });
      const { parentId } = selectedNode;
      if (parentId !== 100 && parentId !== 200 && parentId !== 30000 && parentId !== 30100 && parentId !== 30101 && parentId !== 30200 && !this.checkList.includes(parentId)) {
        this.checkList.push(parentId);
        this.pushAllparentsId(parentId);
      }
    },
    unSelecteSonNode(node) {
      _.each(node, (item) => {
        this.checkList = _.difference(this.checkList, [item.menuId]);
        if (item.children) {
          this.unSelecteSonNode(item.children);
        }
      });
    },
    doFlattenPermissionList(permissionList) {
      let flattenedPermission = [];
      _.each(permissionList, (item) => {
        flattenedPermission.push(item);
        if (item.children) {
          flattenedPermission = flattenedPermission.concat(this.doFlattenPermissionList(item.children));
        }
      });
      return flattenedPermission;
    },
    getSpanMethod({
      row, column, rowIndex, columnIndex,
    }) {
      if (columnIndex === 0) {
        if (_.has(row, '账户类型')) {
          if (rowIndex === 0) {
            return {
              rowspan: 8,
              colspan: 1,
            };
          } if (rowIndex === 8) {
            return {
              rowspan: 8,
              colspan: 1,
            };
          }
          return {
            rowspan: 0,
            colspan: 1,
          };
        } if (_.has(row, '调整类型')) {
          if (rowIndex === 0) {
            return {
              rowspan: 2,
              colspan: 1,
            };
          } if (rowIndex === 2) {
            return {
              rowspan: 8,
              colspan: 1,
            };
          } if (rowIndex === 10) {
            return {
              rowspan: 3,
              colspan: 1,
            };
          }
          return {
            rowspan: 0,
            colspan: 1,
          };
        }
        return {
          rowspan: 1,
          colspan: 1,
        };
      }
    },
    getTableTitle(permissionList) {
      _.each(permissionList, (item) => {
        // 组装选中项
        // if (item.selected === 1) {
        //   this.checkList.push(item.menuId);
        // }
        // 组装表头
        if (!_.find(this.tableTitle, { title: item.tableTitle }) && item.tableTitle !== '数据权限') {
          this.tableTitle.push({ title: item.tableTitle, parentId: item.parentId });
        }
        // 有合并行的情况
        // 会员,代理,加币-计入红利,加币-不计红利,减币
        if ([3010000, 3010001, 3020000, 3020001, 3020002].includes(item.menuId)) {
          this.firstTableTitle = item.tableTitle;
          this.firstNodeObj = {
            menuId: item.menuId, parentId: item.parentId, selected: item.selected, name: item.name, tableTitle: item.tableTitle,
          };
        }
        // 数据权限是最后一级子节点
        if (item.tableTitle === '数据权限') {
          if (![10005, 20005, 20000].includes(item.parentId)) {
            this.sonArray.push({
              menuId: item.menuId, parentId: item.parentId, selected: item.selected, name: item.name, tableTitle: item.tableTitle,
            });
          }

          this.rowObj[item.tableTitle] = this.sonArray;
          if (item.name === '二审' || item.name === '审核' || item.name === '拒绝') {
            if (!_.has(this.rowObj, this.firstTableTitle) && this.firstTableTitle !== '') {
              this.rowObj[this.firstTableTitle] = this.firstNodeObj;
            }
            this.tableData.push(this.rowObj);
            this.rowObj = {};
            this.sonArray = [];
          }
        } else {
          this.rowObj[item.tableTitle] = {
            menuId: item.menuId, parentId: item.parentId, selected: item.selected, name: item.name, tableTitle: item.tableTitle,
          };
          if (item.children) {
            this.getTableTitle(item.children);
          }
        }
      });
    },
    savePermissionList() {
      const fathersId = [1, 100, 2, 200, 3, 300, 30000, 301, 30100, 30101, 302, 30200];
      this.form.menuList = fathersId.concat(this.checkList).join(',');
      this.doSave({ action: 'savePermissionList' });
    },
  },
};
</script>

<style lang="scss" scoped>
  .btn-groups{
      position: absolute;
      right: 10px;
      bottom: -4px;
    }
  .el-col-wrapper{
    position: relative;
    padding-bottom: 64px;
  }
  .select-all{
    position: absolute;
    left: 40px;
    top: 10px;
  }
  .data-menu-wrapper /deep/ .el-submenu {
    &>.el-submenu__title {
      &>span {
        height: auto!important;
        width: auto!important;
        visibility: visible!important;
      }
      .el-submenu__icon-arrow {
        display: block!important;
      }
    }
    & .el-menu-item{
      min-width: auto!important;
    }
  }
  .data-menu-wrapper /deep/ .el-table th.is-left,.data-menu-wrapper /deep/ .el-table tbody tr td:last-child{
    text-align:center!important;
  }
</style>
